package com.patrick.open.api.core.security;

import com.patrick.open.api.core.properties.OpenApiCoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.common.AuthenticationScheme;
import org.springframework.web.client.RestTemplate;

/**
 * @author patrick
 * @date 2020/6/1 10:33 下午
 * @Des 客户端密码模式调用
 * 最簡單的事是堅持，最難的事還是堅持
 */
@Slf4j
public class OauthRestTemplate extends RestTemplate {

  private OpenApiCoreProperties common;

  public OauthRestTemplate(OpenApiCoreProperties common) {
    this.common = common;
  }

  /**
   * 构建网关Oauth2 client_credentials方式请求
   *
   * @return
   */
  public OAuth2RestTemplate buildOAuth2ClientRequest() {
    return buildOAuth2ClientRequest(common.getClientId(), common.getClientSecret(), common.getAccessTokenUri());
  }

  /**
   * 构建网关Oauth2 client_credentials方式请求
   *
   * @param clientId
   * @param clientSecret
   * @param accessTokenUri
   * @return
   */
  public OAuth2RestTemplate buildOAuth2ClientRequest(String clientId, String clientSecret, String accessTokenUri) {
    ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setAccessTokenUri(accessTokenUri);
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource);
    return restTemplate;
  }

  /**
   * 构建网关Oauth2 password方式请求
   *
   * @return
   */
  public OAuth2RestTemplate buildOAuth2PasswordRequest(String username, String password) {
    return buildOAuth2PasswordRequest(common.getClientId(), common.getClientSecret(), common.getAccessTokenUri(), username, password);
  }

  /**
   * 构建网关Oauth2 password方式请求
   *
   * @param clientId
   * @param clientSecret
   * @param accessTokenUri
   * @param username
   * @param password
   * @return
   */
  public OAuth2RestTemplate buildOAuth2PasswordRequest(String clientId, String clientSecret, String accessTokenUri, String username, String password) {
    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
    resource.setUsername(username);
    resource.setPassword(password);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setAccessTokenUri(accessTokenUri);
    resource.setAuthenticationScheme(AuthenticationScheme.form);
    resource.setGrantType("password");
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource);
    log.info("build OAuth2RestTemplate password success");
    return restTemplate;
  }


  public OpenApiCoreProperties getCommon() {
    return common;
  }

  public void setCommon(OpenApiCoreProperties common) {
    this.common = common;
  }
}
